package com.reason.oauth.service.impl;


import com.reason.oauth.service.AuthService;
import com.reason.oauth.utils.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    /**
     * restTemplate发送请求
     */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 注册中心获取资源的对象
     */
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * redis模版类的注入
     */
    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    @Value("${auth.ttl}")
    private long ttl;


    /**
     * 登陆方法
     * @param username
     * @param password
     * @param clientId
     * @param clientSecret
     * @return
     */
    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret,String grant_type) {
        //请求http://localhost:8080/oauth/token获取令牌

        //获取注册中心的服务对象
        ServiceInstance oauth = loadBalancerClient.choose("oauth");
        URI uri = oauth.getUri();
        System.out.println(uri);

        String url=uri+"/oauth/token";//请求路径拼装

        //请求数据的封装
        MultiValueMap multiValueMap=new LinkedMultiValueMap();
        multiValueMap.add("username",username);
        multiValueMap.add("password",password);
        multiValueMap.add("grant_type",grant_type);


        //请求头的封装
        String header= null;
        try {
            header = "Basic "+new String(Base64.getEncoder().encode((clientId+":"+clientSecret).getBytes()),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MultiValueMap headerMap=new LinkedMultiValueMap();
        headerMap.add("Authorization",header);

        //封装到HttpEntity
        HttpEntity httpEntity=new HttpEntity(multiValueMap, headerMap);

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        Map<String ,String> body = response.getBody();
        System.out.println(body);

        //将令牌信息转化成封装的AuthToken
        if(body!=null&&body.size()>0){
            AuthToken authToken = new AuthToken();
            authToken.setAccessToken(body.get("access_token"));
            authToken.setRefreshToken(body.get("refresh_token"));
            authToken.setJti(body.get("jti"));


            //存入redis中
            stringRedisTemplate.boundValueOps(authToken.getJti()).set(authToken.getAccessToken(),ttl, TimeUnit.SECONDS);

            return authToken;


        }

       return null;

    }



}
